//判断机型
let u = navigator.userAgent;

function setupWebViewJavascriptBridge(callback) {
	try{
		const sys = uni.getSystemInfoSync()
		// sys Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.3 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 wechatdevtools/1.06.2308310 MicroMessenger/8.0.5 Language/zh_CN webview/820_49 webdebugger miniprogramhtmlwebview miniProgram port/34592
		console.log('sys--setupWebViewJavascriptBridge', sys.ua)
		
		// sys Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 aweme_14.5.0 JsSdk/2.0 NetType/WIFI Channel/test ByteLocale/zh Region/CN AppTheme/dark Inhouse/1 AwemeInhouse/14.5.0 Mobile bytedanceide/3.0.x ToutiaoMicroApp/1.97.0.7 toutiaodevtools/3.0.x
		if(!sys.ua.includes('miniProgram') || !sys.ua.includes('toutiao')){
			//判断ios 还是Android
			if (/(iPhone|iPad|iPod|iOS)/i.test(u)) {
				console.log('苹果')
				if (window.WebViewJavascriptBridge) {
					return callback(window.WebViewJavascriptBridge)
				}
				if (window.WVJBCallbacks) {
					return window.WVJBCallbacks.push(callback)
				}
				window.WVJBCallbacks = [callback]
				let WVJBIframe = document.createElement('iframe')
				WVJBIframe.style.display = 'none'
				WVJBIframe.src = 'https://__bridge_loaded__'
				document.documentElement.appendChild(WVJBIframe)
				setTimeout(() => {
					document.documentElement.removeChild(WVJBIframe)
				}, 0)
			}
			if (!/(iPhone|iPad|iPod|iOS)/i.test(u)) {
				console.log('安卓')
				try{
					if (window.android) {
						callback(window.android, 'android')
					} else {
						document.addEventListener(
							'android'
							, function() {
								callback(window.android, 'android')
							},
							false
						);
					}
				}catch(err){
					console.log(err)
				}
			}
		}else{
			console.log('没有执行--------------')
		}
	}catch(e){
		//TODO handle the exception
	}
}
export default {
    // 注册回调函数，第一次连接时调用 初始化函数
    initHandler(callback) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.init(function(message, responseCallback) {
                callback(message, responseCallback)
            });
        })
    },
    // 注册事件监听
    registerHandler(name, callback) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.registerHandler(name, function (data, responseCallback) {
				console.log('registerHandler')
                callback(data, responseCallback)
            })
        })
    },
    // 指定方法发送消息给app
    callHandler(name, data, callback) {
		console.log('callHandler',data)
        setupWebViewJavascriptBridge(function (bridge, type) {
			if(type == 'android'){
				bridge[name](JSON.stringify(data))
			}else{
				bridge.callHandler(name, data, callback)
			}
        })
    },
}
